﻿using System;
using System.Collections.Generic;
using System.Reflection;
using DA.AnimGraph;
using UnityEngine;
using UnityEngine.UIElements;

namespace DA.AnimGraph.Editor {
    internal static class SearchDialog {
        public static VisualElement SearchByBlackboardUsing(AGEEnvironment ageEnv) {

            List<SearchResultData> SearchFunction(string searchText) {
                if (string.IsNullOrEmpty(searchText)) return null;

                var bbEntries = ageEnv.ageContext.GetRootHandle().GetBlackboardEntriesBySearch(searchText);
                if (bbEntries == null || bbEntries.Length == 0) return null;
                var linkTypeName = $"AGAFieldModel_{bbEntries[0].type}Link";

                List<SearchResultData> resultList = new();
                foreach (var bbEntry in bbEntries) {
                    ageEnv.ageContext.GetRootHandle().ForeachGraphs(graphHandle => {
                        graphHandle.rootSubGraphHandle.ForeachNodes(nodeHandle => {
                            var agaNodeType = nodeHandle.data.GetType();
                            var modelType = NodeTypeRegister.GetInstance().GetModelTypeOf(agaNodeType);
                            if (modelType == null) return;

                            FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
                            bool isMatch = false;
                            foreach (FieldInfo field in fields) {
                                if (field.FieldType.Name == linkTypeName) {
                                    var linkObj = field.GetValue(nodeHandle.data.modelProperty);

                                    var linkType = linkObj.GetType(); // AGAFieldModel_FloatLink这层
                                    var blackboardKeyField = linkType.GetField("blackboardKey");
                                    D.A(blackboardKeyField != null, $"类型 {linkType} 中不含有成员 blackboardKey");
                                    var blackboardKeyObj = blackboardKeyField.GetValue(linkObj);
                                    var blackboardKey = (AUID)blackboardKeyObj;

                                    if (blackboardKey == bbEntry.uuid) {
                                        isMatch = true;
                                        break;
                                    }
                                } else if (field.Name == "layerDescs") {
                                    // NodeViewInspector_LayerBlend 的Link是嵌套的，上面的逻辑搜索不到，单独处理
                                    var ListObj = field.GetValue(nodeHandle.data.modelProperty) as List<AGAFieldModel_Layer>;
                                    foreach (var eleObj in ListObj) {
                                        if (eleObj.weight.blackboardKey == bbEntry.uuid) {
                                            isMatch = true;
                                            break;
                                        }
                                    }
                                    if (isMatch) break;
                                }
                            }
                            if (isMatch) {
                                resultList.Add(new SearchResultData() {
                                    graphHandle = graphHandle,
                                    nodeHandle = nodeHandle,
                                    searchText = bbEntry.name,
                                });
                            }
                        });
                    });
                }

                return resultList;
            }

            return SearchBase(ageEnv, "Blackboard参数名", SearchFunction);
        }

        public static VisualElement SearchByNodeName(AGEEnvironment ageEnv) {
            List<SearchResultData> SearchFunction(string searchText) {
                if (string.IsNullOrEmpty(searchText)) return null;
                searchText = searchText.ToLower();
                List<SearchResultData> resultList = new();

                ageEnv.ageContext.GetRootHandle().ForeachGraphs(graphHandle => {
                    graphHandle.rootSubGraphHandle.ForeachNodes(nodeHandle => {
                        var nodeName = nodeHandle.GetNodeName();
                        if (string.IsNullOrEmpty(nodeName)) return;
                        if (nodeName.ToLower().Contains(searchText)) {
                            resultList.Add(new SearchResultData() {
                                searchText = searchText,
                                graphHandle = graphHandle,
                                nodeHandle = nodeHandle,
                            });
                        }

                    });
                });
                return resultList;
            }

            return SearchBase(ageEnv, "节点名", SearchFunction);
        }

        public static VisualElement SearchBase(AGEEnvironment ageEnv, string searchLabel, Func<string, List<SearchResultData>> searchFunction) {
            var body = new VisualElement();

            var top = new VisualElement() {
                style = { flexDirection = FlexDirection.Row }
            };
            body.Add(top);

            var inputField = new TextField(searchLabel) {
                style = { flexGrow = 1 }
            };
            top.Add(inputField);

            var button = new Button() {
                text = "搜索",
                style = {
                    minWidth = 100,
                }
            };
            top.Add(button);

            var listView = new ListView() {
                reorderable = false,
                selectionType = SelectionType.Single,
                fixedItemHeight = 40,
                showBorder = true,
                showAlternatingRowBackgrounds = AlternatingRowBackground.All,
            };
            listView.itemsSource = null;
            listView.makeItem = () => new SearchResultView(ageEnv);
            listView.bindItem = (item, index) => {
                if (item is SearchResultView entry) {
                    entry.Show(listView.itemsSource[index] as SearchResultData);
                }
            };
            body.Add(listView);

            button.clicked += () => {
                var resultList = searchFunction(inputField.text);
                listView.itemsSource = resultList;
                listView.Rebuild();
            };
            return body;
        }

        public class SearchResultData {
            public string searchText;
            public AGAHandle_Graph graphHandle;
            public AGAHandle_Node nodeHandle;
        }

        public class SearchResultView : VisualElement {
            private AGEEnvironment ageEnv;
            private SearchResultData data;

            public SearchResultView(AGEEnvironment ageEnv) {
                this.ageEnv = ageEnv;
            }

            public void Show(SearchResultData data) {
                Clear();

                style.flexDirection = FlexDirection.Column;
                var line1 = new VisualElement() {
                    name = "line1",
                    style = {
                        flexDirection = FlexDirection.Row,
                    }
                };
                Add(line1);

                var line2 = new VisualElement() {
                    name = "line2",
                    style = {
                        flexDirection = FlexDirection.Row,
                    }
                };
                Add(line2);

                this.data = data;
                var nodeName = data.nodeHandle.GetNodeName();
                string nameText;
                if (string.IsNullOrEmpty(nodeName)) {
                    nameText = "节点名:_";
                } else {
                    nameText = $"节点名:{nodeName}";
                }
                // 类型
                var nodeTypeTuple = NodeTypeRegister.GetInstance().GetNodeTypeTupleByAGANodeType(data.nodeHandle.agaNodeType);
                var attr = nodeTypeTuple.nodeViewType.GetCustomAttribute<NodeMenuItemAttribute>();
                if (attr != null) {
                    nameText += $" (节点类型:{attr.path})";
                }
                // 搜索文本
                nameText += $" (搜索信息:{data.searchText})";

                var nameField = new Label(nameText) {
                    style = {
                        flexGrow = 1,
                        color = SearchListEntry.highLightColor,
                    }
                };
                line1.Add(nameField);

                var graphHandle = data.nodeHandle.parent.parent as AGAHandle_Graph;
                var graphNameField = new Label(graphHandle.name) {
                    style = {
                        color = SearchListEntry.weakColor,
                    }
                };
                line2.Add(graphNameField);

                var pingButton = new Button() {
                    text = "定位"
                };
                pingButton.clicked += OnPingClicked;
                line1.Add(pingButton);
            }
            private void OnPingClicked() {
                ageEnv.serviceManager.GetService<HierarchyPaneService>()?.OpenGraphByUuid(data.graphHandle.uuid);
                ageEnv.serviceManager.GetService<GraphViewService>()?.SetCenterPosition(data.nodeHandle.position);
            }
        }

    }
}